//
//  NFSWeChatHelper.m
//  NetEaseFinancial
//
//  Created by 吴玉峰 on 8/30/15.
//  Copyright (c) 2015 吴玉峰. All rights reserved.
//

#import "WYFWeChatHelper.h"

#import "WXApi.h"
#import "WYFShareHolder.h"

@interface WYFWeChatHelper () <WXApiDelegate>

@end
@implementation WYFWeChatHelper

- (void)sendToWeChatFriend:(WYFShareHolder *)holder {
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = holder.webUrl;
    [self shareOnWeChatBase:WXSceneSession holder:holder andExtObject:ext];
}

- (void)shareOnWeChatMoment:(WYFShareHolder *)holder {
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = holder.webUrl;

    [self shareOnWeChatBase:WXSceneTimeline holder:holder andExtObject:ext];
}

- (void)sendFileToWeChatFavorite:(WYFShareHolder *)holder {
    NSURL *url = [NSURL URLWithString:holder.dataUrl];
    NSData *fileData = [NSData dataWithContentsOfURL:url];
    WXFileObject *ext = [WXFileObject object];
    ext.fileExtension = holder.sourceType;
    ext.fileData = fileData;

    [self shareOnWeChatBase:WXSceneFavorite holder:holder andExtObject:ext];
}

- (void)shareOnWeChatBase:(enum WXScene)scene holder:(WYFShareHolder *)holder andExtObject:(NSObject *)ext {
    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *imgUrl = [NSURL URLWithString:holder.imgUrl];
        __block UIImage *thumbImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:imgUrl]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf p_shareWithThumImage:holder thumbImage:thumbImage scene:scene extObject:ext];
        });
    });
}

- (void)p_shareWithThumImage:(WYFShareHolder *)holder thumbImage:(UIImage *)thumbImage scene:(enum WXScene)scene extObject:(NSObject *)ext{

    WXMediaMessage *message = [WXMediaMessage message];
    message.title = holder.title;
    message.description = holder.desc;

    [message setThumbImage:thumbImage];
    message.mediaObject = ext;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = scene;
    [WXApi sendReq:req];
}

+ (instancetype)sharedInstance {
    static WYFWeChatHelper *helper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[WYFWeChatHelper alloc] init];

    });
    return helper;
}

- (instancetype)init {

    static id obj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        obj = [super init];
        if (obj) {
        }

    });
    self = obj;
    return self;
}

@end
